package com.docking.heylo.web.interceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/***
 * 辅助Web拦截器
 *
 */
@Component
public class WebInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(logger.isDebugEnabled()){
            Enumeration<String> headerNames = request.getHeaderNames();
            logger.debug(String.format("请求头 [%20s : %-50s]", getIpAddress(request), request.getServletPath()));
            while (headerNames.hasMoreElements()){
                String headerName = headerNames.nextElement();
                logger.debug(String.format("请求头 [%20s : %-50s]", headerName, request.getHeader(headerName)));
            }
        }
        return true;
    }


    /**
     * 获取客户端请求终端地址
     * @param request  客户端请求request
     * @return  终端ip地址
     */
    public String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        System.out.println("X-Forwarded-For : " + ip);
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        System.out.println("X-Real-IP : " + ip);
        if (!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }
}
